<?php
$caption = BUtils::T('restaurants_lbl');
$this->pageTitle = $caption;
if (empty($_GET['tag'])) {
	$this->breadcrumbs=array(
		$caption,
	);
} else {
	$searchTag = isset($GLOBALS['LNG'][$_GET['tag']]) ? $GLOBALS['LNG'][$_GET['tag']] : $_GET['tag'];
	$this->breadcrumbs=array(
		$caption => Yii::app()->createUrl('/'.$this->id),
		$searchTag,
	);
	$this->pageTitle = $caption . '/' . $searchTag;
}

$tags_lbl = BUtils::T('tags_lbl');

//make map data
$default = array();
foreach ($rows as $k => $r) {
	if (!empty($r['latitude'])) {
		$default['lat'] = $r['latitude'];
		$default['lng'] = $r['longitude'];
		break;
	}
}
if (empty($default)) {
	$default['lat'] = 60.15;
	$default['lng'] = 25.03;
}
?>
<div class="row">
	<div class="span7">
		<div class="venueResults box_white clearfix">
			<div id="error_result" class="panel" style="display:none;">
				<h3>Search Error</h3>
				<p>Whoops, something went wrong. Please try again, or if the problem persists, please email <a href="mailto:feedback@yamii.fi">feedback@yamii.fi</a> to report the error.</p>
			</div>
			<div id="success_result">
<?php
$markers = array();
foreach ($rows as $k => $r) {
	$bizLink = Yii::app()->createUrl($this->id.'/view', array('id'=>$r['id']));
	$bizLogoLink = BUtils::GetBusinessPictureUrl($r['url_logo']);
	$bizTagLinks = null;
	$bizTagLinks .= $this->getTagLinks($r['cuisine_style'], ', ');
	if (!empty($bizTagLinks)) $bizTagLinks .= ', ';
	$bizTagLinks .= $this->getTagLinks($r['cuisine_type'], ', ');
	if (!empty($bizTagLinks)) {
		$bizTagLinks = '<span>'.$tags_lbl.'</span>: ' . $bizTagLinks;
	}
	$bizSpecials = null;
	if (!empty($r['specials']) and $r['specials'] > 0) {
		$specialListLink = Yii::app()->createUrl('/special/view', array('id'=>$r['id_special']));
		$tips = ($r['specials'] > 1) ? $r['specials'] . ' ' . BUtils::T('specials_lbl') : $r['specials'] . ' ' . BUtils::T('special_lbl');
		$bizSpecials = '<span class="specialsTab"><a class="link popupBox" href="'.$specialListLink.'" title="'.$tips.'">'.$r['specials'].'</a></span>';
	}
	
	$i = $offset + $k + 1;
	echo <<<HTML
<div class="venueItem clearfix" id="mid_{$r['id']}">
	<div class="bizLogo">
		<a href="{$bizLink}"><img src="{$bizLogoLink}" alt="{$r['name']}" class="img-polaroid" /></a>
	</div>
	<div class="bizLocation">
		<address>
			<div class="street">{$r['address']}</div>
			<div class="city">{$r['postcode']} {$r['city']}</div>
			<div class="phone">{$r['phone']}</div>
		</address>
	</div>
	<div class="bizInfo clearfix">
		<div class="clearfix">
			<div class="bizActions right"></div>
			<h4 class="bizTitle"><a id="bizTitleLink{$i}" href="{$bizLink}">{$i}. {$r['name']}</a> {$bizSpecials}</h4>
		</div>
		<div class="tags clearfix">{$bizTagLinks}</div>
	</div>
</div>
HTML;
	
	//create markers
	$marker = array(
		'id' => $r['id'],
		'lat' => $r['latitude'],
		'lng' => $r['longitude'],
	);
	$marker['body'] = <<<HTML
<div class="place-sider clearfix">
	<div class="bizInfo">
		<div class="name"><a href="{$bizLink}">{$r['name']}</a></div>
		<div class="address">
			<i class="gicon-google-maps gicon-white"></i> <span class="street">{$r['address']}</span><br />
			<i class="gicon-blank"></i> <span class="city">{$r['postcode']} {$r['city']}</span>
		</div>
HTML;
	if (!empty($r['phone'])) {
		$marker['body'] .= '<div class="phone"><i class="gicon-phone gicon-white"></i> '.$r['phone'].'</div></div>';
	}
	$marker['body'] .= '</div></div>';
	if (!empty($marker['lat']) and !empty($marker['lng'])) {
		$markers[] = $marker;
	}
}
?>
			</div>
		</div>
		<div class="btn-group right clearfix">
<?php
if ($page > 1) {
	echo '<a class="btn load-prev" data-offset="'.($offset-20).'" data-page="'.($page-1).'" href="?page='.($page-1).'"><i class="icon-chevron-left"></i> Previous</a>';
} else {
	echo '<a class="btn load-prev" data-offset="'.($offset-20).'" data-page="'.($page-1).'" href="?page='.($page-1).'" style="display:none;"><i class="icon-chevron-left"></i> Previous</a>';
}
echo '<a class="btn load-next" data-offset="'.($offset+20).'" data-page="'.($page+1).'" href="?page='.($page+1).'"><i class="icon-chevron-right"></i> Next</a>';
?>
		</div>
		<div class="clearfix" style="clear:both; margin-bottom:18px;"></div>
	</div>
	<div class="span5" id="sidebar">
		<div class="box_white clearfix">
			<div class="panel">
				<div id="theMapPopup" class="map-popup-fields"></div>
				<div id="theMap" class="map-fields" data-latitude="<?php echo $default['lat']; ?>" data-longitude="<?php echo $default['lng']; ?>" data-zoom="12"></div>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">
<?php
echo 'var markers =' . json_encode($markers) . ';';
?>
var mapCav = null;
var activePinId = null;
$(function() {
	$('.popupBox').colorbox();
	$('.popupBox').tooltip();
	
	//ajax load list
	$('.load-next').click(function () {
		request_list($(this));
		return false;
	});
	$('.load-prev').click(function () {
		request_list($(this));
		return false;
	});
	
	mapCav = $("#theMap").css('height','600px').isMapCanvas('<?php echo Yii::app()->baseUrl; ?>', 1);
	$.map(markers, function(v, i) {
		var pinId = 'mid_' + v.id;
		mapCav.pin(pinId, {style:2,
			latitude: v.lat,
			longitude: v.lng,
			onClick: function() {
				mapInfoWindow(pinId, v);
			}
		});
	});

	//map silder fixed
    $.fn.scrollBottom = function() {
        return $(document).height() - this.scrollTop() - this.height();
    };
	var offsetY = 40;      //the top offset
	var topPosY = 113;     //the top position
	var bottomPosY = 112 + 14;//the bottom position
    var $el = $('#sidebar>div');
    var $window = $(window);
	//call it when scroll or resize
    $window.bind("scroll resize", function() {
		var fullWidth = $('.container').width();
		var silderWidth = $('#sidebar').width();
		if (fullWidth >= 940) {
			$el.css({position: 'fixed', width: silderWidth});//set fixed position
			
			var gap = $window.height() - $el.height() - (offsetY + 0);
			var visibleFoot = (bottomPosY - 20) - $window.scrollBottom();
			var scrollTop = $window.scrollTop()

			if (scrollTop < topPosY - offsetY){
				$el.css({
					top: (topPosY - scrollTop) + "px",
					bottom: "auto"
				});
			} else if (visibleFoot > gap) {
				$el.css({
					top: "auto",
					bottom: visibleFoot + "px"
				});
			} else {
				$el.css({
					top: offsetY,
					bottom: "auto"
				});
			}
		} else {
			$el.css({position: 'inherit', top: null, width:'inherit'})
		}
    });
});


function request_list(_pager) {
	if (_pager.attr('disabled')) return false;
	
	var _request = $.ajax({
		url: location.href,
		type: 'GET',
		data: {offset : _pager.data('offset')},
		dataType: 'json',
		beforeSend: function(xhr) {
			_pager.attr('disabled', true);
		},
		error: function() {
			_pager.attr('disabled', false);
		}
	});
	_request.done(function(msg) {
		if (msg.html == '') {
			location.reload();
			return;
		}
		
		_pager.attr('disabled', false);
		if (_pager.hasClass('load-prev')) {
			var _offset = _pager.data('offset');
			if (_offset > 19) {
				_pager.data('offset', _offset - 20);
				$('.load-next').data('offset', _offset + 20);
			} else {
				_pager.attr('disabled', true);
				_pager.data('offset', 0);
				$('.load-next').data('offset', 20);
			}
			$('.load-next').show().attr('disabled', false);
		} else {
			var _offset = _pager.data('offset');
			if (_offset < 500) {
				if (msg.number < 20) _pager.attr('disabled', true);
				_pager.data('offset', _offset + 20);
				$('.load-prev').data('offset', _offset - 20);
			} else {
				_pager.attr('disabled', true);
				_pager.data('offset', 0);
				$('.load-prev').data('offset', 480);
			}
			$('.load-prev').show().attr('disabled', false);
		}
		
		$('#success_result').html('');
		$('#success_result').append(msg.html);
		
		mapCav.removeAllPins();
		mapCav.removeAllBubbles();
		$.map(msg.markers, function(v, i) {
			var pinId = 'mid_' + v.id;
			mapCav.pin('mid_' + v.id, {
				style:2,
				latitude: v.lat,
				longitude: v.lng,
				onClick: function() {
					mapInfoWindow(pinId, v);
				}
			});
		});
		
		$('#error_result').hide();
	});
	_request.fail(function(jqXHR, textStatus) {
		$('#error_result').show();
		$('#success_result').hide();
	});
}

function mapInfoWindow(pinId, marker) {
	console.log(pinId);
	//clear last activePinId
	mapCav.pin(activePinId, {style:2, zIndex:0});
	activePinId = pinId;
	mapCav.removeAllBubbles();
	mapCav.bubble(pinId, {
		latitude: marker.lat,
		longitude: marker.lng,
		content: marker.body,
		offsetVertical: -4,
		size: 'small'
	});
	mapCav.pin(pinId, {style: 3, zIndex: 9999});
}
</script>